package com.supercube.sport.yoga.controller;

import com.google.common.collect.Lists;
import com.supercube.common.controller.BaseController;
import com.supercube.common.domain.DictDO;
import com.supercube.common.service.DictService;
import com.supercube.common.utils.DateUtils;
import com.supercube.common.utils.QiNiuUtils;
import com.supercube.common.utils.StringUtils;
import com.supercube.sport.yoga.utils.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/commonInfo")
@Api(tags = "common信息")
public class CommonController extends BaseController {

    @Autowired
    private DictService dictService;

    // 图片允许的后缀扩展名
    private static List IMAGE_FILE_ETD = Lists.newArrayList("gif", "png", "bmp", "jpg", "jpeg", "pdf", "avi",
            "mp4", "avi", "rm", "rmvb", "flv", "mpg", "mov", "mkv");

    /**
     * 根据type查询字典信息详情
     *
     * @param type
     * @return
     */
    @ApiOperation(value = "根据type查询字典信息详情", notes = "根据type查询字典信息详情")
    @PostMapping("/queryDictInfoByType")
    public ResultInfo queryDictInfoByType(String type) {
        Map<String, Object> map = new HashMap<>(16);
        if (StringUtils.isNotEmpty(type)) {
            map.put("type", type.trim());
        }
        List<DictDO> dictList = dictService.list(map);
        return ResultInfo.success(dictList);
    }

    @ApiOperation(value = "上传文件到七牛云", notes = "file(String)：文件")
    @PostMapping("/uploadFile")
    public ResultInfo uploadFile(@RequestParam("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int dotPos = originalFilename.lastIndexOf(".");
        if (dotPos < 0) {
            return ResultInfo.failed("上传文件失败");
        }
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 判断是否是合法的文件后缀
        if (!isFileAllowed(suffix)) {
            return ResultInfo.failed("不支持该格式文件，上传文件失败");
        }
        String fileName = DateUtils.getYear() + "/" + DateUtils.getMonth() + "/" + randomUUID() + "." + suffix;
        boolean upload = false;
        try {
            upload = QiNiuUtils.upload(file.getBytes(), fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (upload) {
            return ResultInfo.success(fileName, "上传成功");
        }
        return ResultInfo.failed("上传文件失败");
    }

    public static boolean isFileAllowed(String fileName) {
        if (IMAGE_FILE_ETD.contains(fileName.toLowerCase())) {
            return true;
        }
        return false;
    }
}
